'use client';
import { useTranslations } from 'next-intl';
import { Button, Modal, Table, theme, Checkbox, Form, Input, Radio, message, Popconfirm, Space, Tag, type TableProps, Col, Row } from 'antd';
import { useRouter } from 'next/navigation';
import AvaForm from './AvaForm';
import Layout from '@/components/Layout';
import styles from './index.module.less';
import { useEffect, useState } from 'react';
import type { FormProps, GetProp } from 'antd';
import type { PopconfirmProps } from 'antd';
interface DataType {
  key: string;
  name: string;
  role: string;
  desc: string;
  tags: string[];
}

export default function User() {
  



  const columns: TableProps<DataType>['columns'] = [
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
      fixed: 'left',
      width: 100
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: role => role === '1' ? '超级管理员' : '开发者'
    },
    {
      title: '简介',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => {
            setFormtitle('编辑')

            console.log(record);

            setedit(record)
            setIsModalOpen(true);
          }}>编辑</Button>

          <Popconfirm
            title="删除"
            description="确定删除吗?"
            onConfirm={()=>{
              // data.splice()
              console.log(record.key);
              del(record.key)
              
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data,setdata] = useState([
    {
      key: '1',
      name: '徐小夕',
      role: "1",
      desc: 'H5-Dooring作者, 掘金签约作者，知乎专栏作家',
      tags: ['前端工程师', 'developer'],
    },
    {
      key: '2',
      name: '张三',
      role: "2",
      desc: '知乎专栏作家',
      tags: ['前端工程师', 'developer', 'Dooring'],
    },
    {
      key: '3',
      name: '李盟',
      role: "2",
      desc: 'Dooring共建者',
      tags: ['后端工程师', 'V6.Dooring', 'Dooring'],
    },
    {
      key: '4',
      name: '王阿明',
      role: "2",
      desc: '技术合伙人',
      tags: ['全栈工程师', '橙子表单'],
    },
    {
      key: '5',
      name: '张小明',
      role: "2",
      desc: '技术合伙人',
      tags: ['全栈工程师', '橙子表单'],
    },
    {
      key: '6',
      name: 'Tom',
      role: "2",
      desc: '技术合伙人',
      tags: ['全栈工程师', 'Next-Admin'],
    },
    {
      key: '7',
      name: 'Json',
      role: "2",
      desc: '技术合伙人',
      tags: ['全栈工程师', 'Next-Admin'],
    },
  ]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  let [Formtitle, setFormtitle] = useState('')
  let [Formedit, setedit] = useState({})//编辑

  const showModal = () => {
    setFormtitle('添加')
    setedit({})
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  type FieldType = {
    key?: string;
    name?: string;
    role?: string;
    desc?: string;
    tags?: string;
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    const key = Date.now().toString()
    if (Formtitle == '添加') {
      // const twoData={...data}
      // twoData.push(values,key )
      // console.log(twoData);
      data.push({ ...values, key })
      console.log(data);
    }
    if(Formtitle == '编辑'){
      let index=data.findIndex(item=>item.key==Formedit.key)
      console.log(index,'index');
      
      data[index]={...Formedit,...values}
      console.log(data[index]);
    }
    setIsModalOpen(false);
  };




  const t = useTranslations('yzh');
  const { token } = theme.useToken();

  const listStyle: React.CSSProperties = {
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    padding: 12
  };

  const plainOptions = ['前端工程师', '后端工程师', '全站工程师', '高薪工程师'];


  const onChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
    console.log('checked = ', checkedValues);
  };
  const [form] = Form.useForm();
  console.log(form);
  useEffect(() => {
    form.setFieldsValue(Formedit)
    console.log(form);

  }, [Formedit])

  const del=(key:string)=>{
    let cc=data.filter(item=>{
      return item.key!==key
    })
    setdata(cc)
    
  }



  return (
    <Layout curActive='/yzh'>
      <main className={styles.userWrap}>

        <Button type="primary" onClick={showModal}>
          添加
        </Button>
        <Modal title={Formtitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
          <Form
            form={form}
            key={new Date().getTime()}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
          >

            <Form.Item<FieldType>
              label="用户名"
              name="name"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="角色"
              name="role"
              rules={[{ required: true, message: '请选择你的角色!' }]}
            >
              <Radio.Group>
                <Radio value="1"> 超级管理员 </Radio>
                <Radio value="2"> 开发者 </Radio>
              </Radio.Group>
            </Form.Item>



            <Form.Item<FieldType>
              label="简介"
              name="desc"
              rules={[{ required: true, message: '请输入你的简介!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType >
              label="标签"
              name="tags"
              rules={[{ required: true, message: '请选择你的标签!' }]}
            >
              {/* <Checkbox.Group options={tags}  /> */}
              <Checkbox.Group options={plainOptions}>
                <Row>
                  <Col span={16}>
                    <Checkbox value="前端工程师" style={{ lineHeight: '32px' }}>
                      前端工程师
                    </Checkbox>
                  </Col>
                  <Col span={16}>
                    <Checkbox value="后端工程师" style={{ lineHeight: '32px' }} >
                      后端工程师
                    </Checkbox>
                  </Col>
                  <Col span={16}>
                    <Checkbox value="全站工程师" style={{ lineHeight: '32px' }}>
                      全站工程师
                    </Checkbox>
                  </Col>
                  <Col span={16}>
                    <Checkbox value="高薪工程师" style={{ lineHeight: '32px' }}>
                      高薪工程师
                    </Checkbox>
                  </Col>

                </Row>
              </Checkbox.Group>
            </Form.Item>



            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <div className={styles.content}>
          <AvaForm />
          <div style={listStyle}>
            <h3>{t('yzh')}</h3>
            <Table key={new Date().getTime()} columns={columns} dataSource={data} pagination={{ pageSize: 5 }} scroll={{ x: 1000 }} />
          </div>
        </div>
      </main>
    </Layout>

  );
}
